<template>
  <div id="loginbody">
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/login">页面</a>
            <span class="breadcrumb-item active" aria-current="page">登录</span>
          </nav>
          <h1>登录</h1>
        </div>
      </div>
    </section>

    <section class="py-5 my-5">
      <div class="container-sm">
        <div class="row justify-content-center">
          <div class="col-lg-6 d-flex align-items-end">
            <img src="@/assets/images/img-login.jpg" alt="Login" class="img-fluid">
          </div>
          <div class="col-lg-6 p-5 bg-white border shadow-sm">
            <h5 class="text-uppercase mb-4">登录</h5>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="用户名登录" name="userName">
                <el-form ref="form" :model="ruleForm" :rules="rules">
                  <div class="col-12 pb-3">
                    <label class="d-none">用户名*</label>
                    <input type="text" v-model="ruleForm.userName" placeholder="用户名" class="form-control">
                  </div>
                  <div class="col-12 pb-3">
                    <label class="d-none">密码 *</label>
                    <input type="password" v-model="ruleForm.password" placeholder="密码" class="form-control">
                  </div>
                  <div class="col-12 pb-3">
                    <button type="button" @click="submitForm('userName')" class="btn btn-primary text-uppercase w-100">登录</button>
                  </div>
                  <div class="col-12 pb-3">
                    <label>
                      <input type="checkbox" required="">
                      <span class="label-body">记住我</span>
                    </label>
                  </div>
                  <div class="col-12">
                    <p><a href="/Organic/registered" >注册</a></p>
                  </div>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="手机号登录" name="phoneNumber">
                <el-form ref="form" :model="ruleForm" :rules="rules">
                  <div class="col-12 pb-3">
                    <label class="d-none">Phone Number *</label>
                    <input type="text" v-model="ruleForm.phoneNumber" placeholder="手机号" class="form-control">
                  </div>
                  <div class="col-12 pb-3 d-flex">
                    <input type="text" v-model="ruleForm.verificationCode" placeholder="验证码" class="form-control me-2">
                    <button type="button" @click="sendVerificationCode" :disabled="isCountingDown" class="btn btn-secondary text-uppercase">
                      {{ isCountingDown ? `${countdown}秒后重试` : '发送验证码' }}
                    </button>
                  </div>
                  <div class="col-12 pb-3">
                    <button type="button" @click="submitForm('phoneNumber')" class="btn btn-primary text-uppercase w-100">登录</button>
                  </div>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'LoginBody',
  components: {},
  props: {},
  data () {
    return {
      user: {},
      code: '',
      activeName: 'userName',
      ruleForm: {
        userName: '',
        password: '',
        phoneNumber: '',
        verificationCode: ''
      },
      rules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur'}
        ],
        verificationCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {len: 6, message: '验证码长度为6位', trigger: 'blur'}
        ]
      },
      lastSendTime: null, // 记录上次发送验证码的时间
      codeExpireTime: null, // 记录验证码的过期时间
      countdown: 60, // 倒计时时间
      isCountingDown: false // 是否处于倒计时状态
    }
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    submitForm(type) {
      if (type === 'userName') {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let formData = new FormData();
            formData.append('loginName', this.ruleForm.userName);
            formData.append('password', this.ruleForm.password);
            // this.$axios.post('http://localhost:8090/consumer/login', formData)
            this.$axios.post('/api/consumer/login', formData)
                .then(({ data }) => {
                  if (data !== null && data !== undefined && data !== '') {
                    this.$notify({
                      title: '登录成功',
                      message: '欢迎登录！'+data.nickName,
                      type: 'success'
                    });
                    this.$store.commit('initUser', data);
                    this.user = data;
                    this.intCart();
                    window.location.href = '/Organic/home';
                  } else {
                    // this.$message({ message: '用户名或密码错误', type: 'warning' });
                    this.$notify({
                      title: '登录失败',
                      message: '用户名或密码错误',
                      type: 'warning'
                    });
                  }
                })
                .catch(error => {
                  console.error(error);
                  // this.$message({ message: '登录失败，请稍后重试', type: 'error' });
                  this.$notify({
                    title: '登录失败',
                    message: '登录失败，请稍后重试',
                    type: 'error'
                  });
                });
          } else {
            console.log('用户名登录验证失败');
          }
        });
      } else if (type === 'phoneNumber') {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.codeExpireTime && new Date().getTime() > this.codeExpireTime) {
              // this.$message({ message: '验证码已过期，请重新获取', type: 'warning' });
              this.$notify({
                title: '验证码已过期',
                message: '请重新获取验证码',
                type: 'warning'
              });
              return;
            }
            if (this.code !== this.ruleForm.verificationCode) {
              // this.$message({ message: '手机号或验证码错误', type: 'warning' });
              this.$notify({
                title: '手机号或验证码错误',
                message: '请重新输入手机号或验证码',
                type: 'warning'
              });
            } else {
              this.$axios.get('http://localhost:8090/consumer/loginByPhone?phone=' + this.ruleForm.phoneNumber)
                  .then(({ data }) => {
                    if (data != null) {
                      this.$store.commit('initUser', data);
                      window.location.href = '/Organic/home';
                    } else {
                      // this.$message({ message: '该手机号还为注册账号', type: 'warning' });
                      this.$notify({
                        title: '该手机号还为注册账号',
                        message: '请重新输入手机号或验证码',
                        type: 'warning'
                      });
                    }
                  })
                  .catch(error => {
                    console.error(error);
                    // this.$message({ message: '登录失败，请稍后重试', type: 'error' });
                    this.$notify({
                      title: '登录失败',
                      message: '登录失败，请稍后重试',
                      type: 'error'
                    });
                  });
            }
          } else {
            console.log('手机号登录验证失败');
          }
        });
      }
    },
    sendVerificationCode() {
      if (!this.ruleForm.phoneNumber) {
        this.$message({ message: '请输入手机号', type: 'warning' });
        return;
      }
      const currentTime = new Date().getTime();
      if (this.lastSendTime && currentTime - this.lastSendTime < 60000) {
        // this.$message({ message: '请等待1分钟后再获取验证码', type: 'warning' });
        this.$notify({
          title: '请等待1分钟后再获取验证码',
          message: '请稍后重试',
          type: 'warning'
        });
        return;
      }
      this.code = Math.random().toString().slice(2, 6);
      this.lastSendTime = currentTime;
      this.codeExpireTime = currentTime + 180000; // 3分钟有效期
      this.isCountingDown = true;
      this.startCountdown();
      this.$axios.post('http://localhost:8090/sms/sendValidateCode', { phoneNumber: this.ruleForm.phoneNumber, code: this.code })
          .then(({ data }) => {
            if (data) {
              // this.$message({ message: '验证码已发送，请查收', type: 'success' });
              this.$notify({
                title: '验证码已发送',
                message: '请查收',
                type: 'success'
              });
            } else {
              // this.$message({ message: '验证码发送失败，请稍后重试', type: 'error' });
              this.$notify({
                title: '验证码发送失败',
                message: '请稍后重试',
                type: 'error'
              });
            }
          })
          .catch(error => {
            console.error(error);
            // this.$message({ message: '验证码发送失败，请稍后重试', type: 'error' });
            this.$notify({
              title: '验证码发送失败',
              message: '请稍后重试',
              type: 'error'
            });
          });
    },
    startCountdown() {
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isCountingDown = false;
          this.countdown = 60;
        }
      }, 1000);
    },
    intCart(){
      this.$axios.get('http://localhost:8090/cart/getCartByConsumerId?consumerId=' + this.user.consumerId).then(({ data }) => {
        // eslint-disable-next-line no-empty
        if(data !== null && data !== undefined ){
          this.$store.commit('initCarts', data)
          console.log(this.$store.state.carts)
        }
      })
    },
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合

  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>

<style scoped>
.btn-secondary {
  white-space: nowrap; /* 确保按钮文字不换行 */
}
</style>
